from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
import os
from configs.settings import *
from utils.ai_translator.model.glm_model import *
from utils.ai_translator.translator.pdf_translator import *

model_name = MODEL_SETTINGS.get("model")
api_key = MODEL_SETTINGS.get("api_key")

app = Flask(__name__)
CORS(app)  # 在 Flask 应用程序中启用 CORS

UPLOAD_FOLDER = 'files'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER


@app.route('/upload', methods=["POST"])
def upload():
    # 检查是否有文件被上传
    if 'file' not in request.files:
        return jsonify({"code": -1, 'msg': 'No file part'})

    file = request.files['file']
    # 检查文件名是否为空
    if file.filename == '':
        return jsonify({"code": -1, 'msg': 'No selected file'})

    if file and allowed_file(file.filename):
        # 可以将文件保存到指定位置，或者进行其他处理
        # 这里我们简单地返回文件名和文件大小
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
        file.save(filepath)
        model_obj = GLMModel(api_key, model_name)

        pdf_translator_obj = PDFTranslator(model_obj, filepath)
        language = pdf_translator_obj.get_book_language()
        language_list = ["中文", "英语", "法语", "日语", "德语"]
        language_list.remove(language)

        return jsonify({
            "code": 0,
            "data": {'filename': file.filename, 'filesize': len(file.read()), "language": language,
                     "language_list": language_list, "filepath": filepath}
        })
    else:
        return jsonify({"code": -1, 'msg': 'File type not allowed'})


@app.route('/start', methods=["POST"])
def start():
    req = request.json
    if not (req.get("filepath") and req.get("to_language")):
        return jsonify({"code": -1, 'msg': 'filepath and to_language cannot be empty'})
    try:
        model_obj = GLMModel(api_key, model_name)
        pdf_translator_obj = PDFTranslator(model_obj, req.get("filepath"), target_language=req.get("to_language"))
        pdf_translator_obj.translate_pdf()
    except Exception as e:
        LOG.error(e)
        return jsonify({"code": -1, 'msg': str(e)})

    return jsonify({"code": 0, 'data': {"output_path": req.get("filepath").replace(".pdf", "_translated.md")}})


@app.route('/download')
def download():
    filepath = request.args.get('filepath')
    return send_file(filepath, as_attachment=True)


def allowed_file(filename):
    ALLOWED_EXTENSIONS = {'pdf'}
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


if __name__ == '__main__':
    app.run()
